package com.ruicar.afs.cloud.afscase.approvetask.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.ApproveMakeLabel;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.ApproveMakeLabelService;
import com.ruicar.afs.cloud.afscase.approvetask.condition.WorkTaskPoolCondition;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.ApproveTaskVo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCarInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.LabelPositionEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ProcessTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author jiaqi.guo
 * @version 1.0
 * @description:公共任务池
 * @created 2020/5/27 14:31
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("公共任务")
@RequestMapping("/approve")
public class CommonPoolTaskController {

    private WorkTaskPoolService workTaskPoolService;

    private CaseCarInfoService caseCarInfoService;

    private CaseBaseInfoService caseBaseInfoService;

    private CaseApproveRecordService caseApproveRecordService;

    private ApproveMakeLabelService approveMakeLabelService;


    @PostMapping(value = "/queryCommonPoolTaskList")
    @ApiOperation(value = "多条件分页获取待审核任务--仅展示当前登录用户的待审核任务，组长可以查看本组")
    public IResponse<IPage<ApproveTaskVo>> queryCommonPoolTaskList(@ModelAttribute WorkTaskPoolCondition condition) {

        //流程类型条件
        List processList = new ArrayList();

        processList.add(ProcessTypeEnum.FORMAL_REVIEW.getCode());
        processList.add(ProcessTypeEnum.GENERA_APPROVE.getCode());
        condition.setProcessTypeList(processList);

        //常规审批
        List generaList = new ArrayList();
        generaList.add(ProcessTypeEnum.GENERA_APPROVE.getCode());
        condition.setGeneraApproveList(generaList);

        //正式复议
        List formalList = new ArrayList();
        formalList.add(ProcessTypeEnum.FORMAL_REVIEW.getCode());
        condition.setFormalReviewList(formalList);
        //获取标签Id
        String[] str = condition.getTag();
        List labelIdList = new ArrayList();
        if (str!=null&&str.length>0) {
            for (int i = 0; i < str.length; i++) {
                labelIdList.add(str[i]);
            }
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        //判断处理人条件是否是拼音
        if (condition.getDisposeStaff().matches("^[a-zA-Z]*")) {
            condition.setDisposeStaffName(condition.getDisposeStaff());
            condition.setDisposeStaff("");
        }

        //业务状态（内）
        List statusList = new ArrayList();
        statusList.add(AfsEnumUtil.key(BusinessStateInEnum.APPROVED));
        statusList.add(AfsEnumUtil.key(BusinessStateInEnum.CONDITIONAL_APPROVE));
        statusList.add(AfsEnumUtil.key(BusinessStateInEnum.REJECT));
        statusList.add(AfsEnumUtil.key(BusinessStateInEnum.REPEAL));
        statusList.add(AfsEnumUtil.key(BusinessStateInEnum.CANCEL_ADVICE_CONDITIONAL));
        condition.setBusinessStatusList(statusList);

        IPage<ApproveTaskVo> pageResult = workTaskPoolService.queryCommonPoolTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);

        pageResult.getRecords().forEach(approveTaskVo -> {
            /**案件基础信息*/
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**车辆信息*/
            CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, approveTaskVo.getApplyNo()));
            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                // 当前时间，毫秒
                Long nowMilliSeconds = System.currentTimeMillis();
                // 开始时间，毫秒
                Long submitDateMilliSeconds = approveTaskVo.getStartTime().getTime();
                Long effectTimeReckon = caseBaseInfo.getEffectTimeReckon();
                int seconds = Convert.toInt((effectTimeReckon + nowMilliSeconds - submitDateMilliSeconds) / 1000, 0);
                String hour = StringUtils.leftPad(seconds / 3600 + "", 2, '0');
                String minute = StringUtils.leftPad((seconds % 3600) / 60 + "", 2, '0');
                String second = StringUtils.leftPad((seconds % 3600) % 60 + "", 2, '0');
                // 原始读秒
                approveTaskVo.setOriginalSeconds(seconds);
                // 计时时间，页面初始化时显示
                approveTaskVo.setTimming(hour + " : " + minute + " : " + second);
                // 拼接车辆信息显示
            }
            if (Objects.nonNull(caseCarInfo)) {
                approveTaskVo.setCarName(caseCarInfo.getModelName());
            }
            /**  标签信息 **/
            List<ApproveMakeLabel> labelList = approveMakeLabelService.list(Wrappers.<ApproveMakeLabel>query().lambda()
                    .eq(ApproveMakeLabel::getApplyNo, approveTaskVo.getApplyNo())
                    .eq(ApproveMakeLabel::getLabelLocation, LabelPositionEnum.LIST.getCode()));
            approveTaskVo.setLabelList(labelList);
        });
        return IResponse.success(pageResult);

    }
}
